var mongodb = require('./db');
var moment = require('moment');
function Report(username, report, time) {
	this.user = username;
	this.report = report;
	if (time) {
		this.time = time;
	} else {
		this.time = moment().format('YYYY-MM-DD HH:mm:ss');
	}
};
module.exports = Report;

Report.prototype.save = function save(callback) {
	var report = {
		user : this.user,
		report : this.report,
		time : this.time,
	};

	mongodb.open(function(err, db) {
		if (err) {
			return callback(err);
		}

		db.collection('reports', function(err, collection) {
			if (err) {
				mongodb.close();
				return callback(err);
			}

			collection.ensureIndex('user');

			collection.insert(report, {
				safe : true
			}, function(err, report) {
				mongodb.close();
				callback(err, report);
			});
		});
	});
};

Report.get = function get(username, page, callback) {
	console.log('page=' + page);
	mongodb.open(function(err, db) {
		if (err) {
			return callback(err);
		}

		db.collection('reports', function(err, collection) {
			if (err) {
				mongodb.close();
				return callback(err);
			}

			var query = {};
			if (username) {
				query.user = username;
			}
			collection.find(query).count(
					function(err, count) {
						if (err) {
							mongodb.close();
							return callback(err);
						}
						if (count > 0) {
							collection.find(query).sort({
								time : -1
							}).limit(10).skip((page - 1) * 10).toArray(
									function(err, docs) {
										mongodb.close();
										if (err) {
											callback(err, null);
										}

										var reports = [];
										docs.forEach(function(doc, index) {
											var report = new Report(doc.user,
													doc.report, doc.time);
											reports.push(report);
										});
										callback(null, reports,count);
									});
						} else {
							var reports = [];
							callback(null, reports, count);
						}
					});
		});
	});
};